import os
import json
import requests
from configparser import ConfigParser
from .logger import logger

class HttpClient:
    def __init__(self):
        # 读取配置
        self.config = ConfigParser()
        self.config.read(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', 'config.ini'), encoding='utf-8')
        
        self.base_url = self.config.get('API', 'base_url')
        self.timeout = int(self.config.get('API', 'timeout'))
        self.session = requests.Session()
        
    def send_request(self, method, url, **kwargs):
        """
        发送HTTP请求
        :param method: 请求方法 (get, post, put, delete等)
        :param url: 请求URL (可以是相对路径)
        :param kwargs: 其他请求参数 (params, data, json, headers等)
        :return: 响应对象
        """
        # 拼接完整URL
        if not url.startswith('http'):
            url = f"{self.base_url}{url}"
        
        # 转换method为小写
        method = method.lower()
        
        logger.info(f"发送{method.upper()}请求: {url}")
        logger.info(f"请求参数: {json.dumps(kwargs, ensure_ascii=False)}")
        
        try:
            # 根据请求方法发送请求
            if method == 'get':
                response = self.session.get(url, timeout=self.timeout,** kwargs)
            elif method == 'post':
                response = self.session.post(url, timeout=self.timeout, **kwargs)
            elif method == 'put':
                response = self.session.put(url, timeout=self.timeout,** kwargs)
            elif method == 'delete':
                response = self.session.delete(url, timeout=self.timeout, **kwargs)
            else:
                logger.error(f"不支持的请求方法: {method}")
                raise ValueError(f"不支持的请求方法: {method}")
            
            logger.info(f"响应状态码: {response.status_code}")
            logger.info(f"响应内容: {response.text}")
            
            return response
            
        except Exception as e:
            logger.error(f"请求发送失败: {str(e)}")
            raise
    
    def close(self):
        """关闭会话"""
        self.session.close()
        logger.info("HTTP会话已关闭")
